package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.LOCK_SHOP_KEY;

@Component
public class RedisTools {

     @Resource
     private StringRedisTemplate stringRedisTemplate;

     //存入redis
     public void setRedis(String key,Object value,Long time,TimeUnit timeUnit){
          String json = JSONUtil.toJsonStr(value);
          stringRedisTemplate.opsForValue().set(key,json,time, timeUnit);
     }

     //设置逻辑过期
     public void setWithLogicalExpire(String key,Object value,Long time,TimeUnit unit){
          RedisData redisData=new RedisData();
          redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
          redisData.setData(value);
          stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
     }

    /**
     *
     * @param id
     * @param type
     * @param dbFallBack,调用的时候传入方法
     * @param time
     * @param timeUnit
     * @param <R>
     * @param <ID>
     * @return
     */
     //缓存穿透   R为返回值类型
     public <R,ID> R  queryWithPassThrough(ID id, Class<R> type, Function<ID,R> dbFallBack,Long time,TimeUnit timeUnit) {
        String key=CACHE_SHOP_KEY + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //判断缓存数据是否不为空
        if (StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json,type);
        }
        //空字符串表示是我们为了解决缓存穿透而存入的
        if (Objects.equals(json, "")){
            return null;
        }
        //根据传入的方法和id查询数据库
        R r =dbFallBack.apply(id);
        if (r==null){
            stringRedisTemplate.opsForValue().set(key,"",time,timeUnit);//下次查到空数据直接返回
            return null;
        }
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(r),time, TimeUnit.MINUTES);
        return r;
    }


    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);//创建包含10个线程的线程池
    //逻辑过期解决缓存击穿
    public <ID,R> R queryWithLogicalExpire(String keyPrefix,ID id, Class<R> type,Function<ID,R> dbFallBack,Long time,TimeUnit timeUnit) {
        String key = keyPrefix + id;
        String jsonString = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(jsonString)) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(jsonString, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {  //说明过期了
            return r;
        }
        String lockKey = LOCK_SHOP_KEY + id;
        //获取互斥锁
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            //开启独立线程重建缓存
            CACHE_REBUILD_EXECUTOR.submit(()->{   //Lambda表达式,箭头左侧表示参数，右侧表示要执行的功能
             try{
                 R r1 = dbFallBack.apply(id); //获得Shop对象
                 setWithLogicalExpire(key,r1,time,timeUnit);}
             catch (Exception e){
                 throw new RuntimeException();
             }
             finally {
                 unLock(lockKey);
             }
            });
        }
        return r;//说明已经有线程在重建缓存，直接返回旧数据
    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);//上面的方法返回值为Boolean，是boolean的包装类，在拆箱的过程中可能会产生null，报空指针异常。
    }

    private void unLock(String key){stringRedisTemplate.delete(key);}

}
